package cn.zsssgjcx.hjsg.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavArgument;
import androidx.navigation.NavGraph;
import androidx.navigation.Navigation;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.android.gms.location.FusedLocationProviderClient;

import java.util.ArrayList;
import java.util.List;

import cn.zsssgjcx.hjsg.R;
import cn.zsssgjcx.hjsg.activity.CityPickActivity;
import cn.zsssgjcx.hjsg.activity.MainActivity;
import cn.zsssgjcx.hjsg.activity.SearchActivity;
import cn.zsssgjcx.hjsg.adapter.BusAdapter;
import cn.zsssgjcx.hjsg.model.BusInfo;
import cn.zsssgjcx.hjsg.utils.AMapUtils;
import cn.zsssgjcx.hjsg.utils.ToastUtils;


public class HomeFragment extends Fragment implements GeocodeSearch.OnGeocodeSearchListener, View.OnClickListener, AMap.OnMarkerClickListener {
    private List<BusInfo> list;
    private BusAdapter busAdapter;
    private ListView listView;
    private Button btn_search;

    private LinearLayout lv_city;

    private FusedLocationProviderClient fusedLocationClient;

    private GeocodeSearch geocoderSearch;
    private String addressName;
    private AMap aMap;
    private LatLonPoint latLonPoint = new LatLonPoint(39.90865, 116.39751);
    private String cityName;
    private String cityCode;
    private Context mcontext;

    private TextView tv_to_city_list,tv_city;

    private LinearLayout ll_no_city,ll_show_city;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mcontext = getContext();
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        listView = view.findViewById(R.id.lv_bus);
        btn_search = view.findViewById(R.id.btn_search);
        lv_city = view.findViewById(R.id.lv_city);
        tv_to_city_list = view.findViewById(R.id.tv_to_city_list);
        tv_city = view.findViewById(R.id.tv_city);
        ll_no_city = view.findViewById(R.id.ll_no_city);
        ll_show_city = view.findViewById(R.id.ll_show_city);

        list = new ArrayList<>();
        list.add(new BusInfo());
        list.add(new BusInfo());

        busAdapter = new BusAdapter(getContext(),list);
        listView.setAdapter(busAdapter);

        initData();

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), SearchActivity.class);
                getContext().startActivity(intent);
            }
        });

        lv_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), CityPickActivity.class);
                getContext().startActivity(intent);
            }
        });

        return view;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLastLocation();
            }
        }
    }

    /**
     * 地理编码查询回调
     */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
    }

    /**
     * 逆地理编码回调
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        //dismissDialog();
        Log.i("Test","---rCode="+rCode);
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                addressName = result.getRegeocodeAddress().getFormatAddress();
//                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
//                        AMapUtils.convertToLatLng(latLonPoint), 15));

                //regeoMarker.setPosition(AMapUtils.convertToLatLng(latLonPoint));

                //ToastUtils.show(addressName);
                Log.i("Test","---addressName="+addressName);

                cityCode = result.getRegeocodeAddress().getCityCode();
                cityName = result.getRegeocodeAddress().getCity();

                Log.i("Test","---cityCode="+cityCode);
                Log.i("Test","---cityName="+cityName);
                ll_no_city.setVisibility(View.GONE);
                ll_show_city.setVisibility(View.VISIBLE);
                tv_city.setText(cityName);

            } else {
                //ToastUtils.show(R.string.no_result);
                Log.i("Test","对不起，没有搜索到相关数据！");
            }
        } else {
            //ToastUtils.show(rCode);
            Log.i("Test","rCode=="+rCode);
        }
    }

    @Override
    public void onClick(View v) {

    }



    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }


    private void initData(){
        ToastUtils.init(getContext());
        privacyCompliance();
        try {
            geocoderSearch = new GeocodeSearch(mcontext);
            geocoderSearch.setOnGeocodeSearchListener(this);
        } catch (AMapException e) {
            throw new RuntimeException(e);
        }
    }

    private void privacyCompliance() {
        MapsInitializer.updatePrivacyShow(mcontext,true,true);
        SpannableStringBuilder spannable = new SpannableStringBuilder("\"亲，感谢您对XXX一直以来的信任！我们依据最新的监管要求更新了XXX《隐私权政策》，特向您说明如下\n1.为向您提供交易相关基本功能，我们会收集、使用必要的信息；\n2.基于您的明示授权，我们可能会获取您的位置（为您提供附近的商品、店铺及优惠资讯等）等信息，您有权拒绝或取消授权；\n3.我们会采取业界先进的安全措施保护您的信息安全；\n4.未经您同意，我们不会从第三方处获取、共享或向提供您的信息；\n");
        spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 35, 42, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        new AlertDialog.Builder(mcontext)
                .setTitle("温馨提示(隐私合规示例)")
                .setMessage(spannable)
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        MapsInitializer.updatePrivacyAgree(mcontext,true);
                        getLastLocation();
                    }
                })
                .setNegativeButton("不同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        MapsInitializer.updatePrivacyAgree(mcontext,false);
                    }
                })
                .show();
    }

    private void getLocation(){
        // 创建AMapLocationClient实例
        AMapLocationClient mLocationClient = null;
        try {
            mLocationClient = new AMapLocationClient(mcontext);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 初始化AMapLocationClientOption对象
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        // 设置定位模式为高精度模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 设置定位间隔，单位毫秒，默认为2000ms，最低1000ms
        mLocationOption.setInterval(2000);
        // 设置定位监听
        mLocationClient.setLocationListener(mLocationListener);
        // 绑定AMapLocationClientOption对象
        mLocationClient.setLocationOption(mLocationOption);
        // 启动定位
        mLocationClient.startLocation();
    }

    private void getLastLocation() {
        if (ContextCompat.checkSelfPermission(mcontext, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
//            Task<Location> task = fusedLocationClient.getLastLocation();
//            task.addOnSuccessListener(new OnSuccessListener<Location>() {
//                @Override
//                public void onSuccess(Location location) {
//                    if (location != null) {
//                        // 使用位置数据
//                        double latitude = location.getLatitude();
//                        double longitude = location.getLongitude();
//                        // ...
//                        Log.d("Test","----latitude="+latitude);
//                        Log.d("Test","----longitude="+longitude);
//                    }
//                }
//            });



//            try{
//                GeocodeSearch geocoderSearch = new GeocodeSearch(this);
//                geocoderSearch.setOnGeocodeSearchListener((GeocodeSearch.OnGeocodeSearchListener) this);
//
//                // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
//                RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(1,1), 200,GeocodeSearch.AMAP);
//
//                geocoderSearch.getFromLocationAsyn(query);
//
//            }catch (AMapException ex){
//
//            }

            getLocation();

        }
    }


    public void getAddress(final LatLonPoint latLonPoint) {
        //showDialog();
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系

        geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求


    }

    // 创建定位监听
    AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    // 获取当前定位结果
                    double latitude = aMapLocation.getLatitude(); // 纬度
                    double longitude = aMapLocation.getLongitude(); // 经度
                    String address = aMapLocation.getAddress(); // 地址信息
                    // 可以在这里对获取的位置信息进行处理
                    Log.i("Test","----latitude="+latitude);
                    Log.i("Test","----longitude="+longitude);
                    Log.i("Test","----address="+address);

                    LatLonPoint latLonPoint = new LatLonPoint(latitude,longitude);
                    getAddress(latLonPoint);
                } else {
                    // 定位失败，显示错误信息
                    Log.e("AmapError", "location Error, ErrCode:" + aMapLocation.getErrorCode() + ", errInfo:" + aMapLocation.getErrorInfo());
                }
            }
        }

    };
}